package com.zt.questionnaire.common.typehandler;

import com.alibaba.fastjson.JSONObject;
import com.zt.questionnaire.common.utils.JsonUtils;
import com.zt.questionnaire.db.entity.ReportEntity;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class EntityReportAnswerListTypeHandler extends BaseTypeHandler<List<ReportEntity.Answer>> {

    private String toJson(List<ReportEntity.Answer> list) {
        try {
            return JSONObject.toJSONString(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<ReportEntity.Answer> toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return JsonUtils.toList(content, ReportEntity.Answer.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }

    @Override
    public List<ReportEntity.Answer> getNullableResult(ResultSet rs, String arg1) throws SQLException {
        // TODO Auto-generated method stub
        return this.toObject(rs.getString(arg1));
    }

    @Override
    public List<ReportEntity.Answer> getNullableResult(ResultSet rs, int arg1) throws SQLException {
        // TODO Auto-generated method stub
        return this.toObject(rs.getString(arg1));
    }

    @Override
    public List<ReportEntity.Answer> getNullableResult(CallableStatement cs, int arg1) throws SQLException {
        // TODO Auto-generated method stub
        return this.toObject(cs.getString(arg1));
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int arg1, List<ReportEntity.Answer> arg2, JdbcType arg3) throws SQLException {
        ps.setString(arg1, this.toJson(arg2));
    }

}
